package backend_0011_1;

import com.sun.source.tree.SynchronizedTree;

import java.util.concurrent.locks.ReentrantLock;

public class Concurrency {
    public static void main(String[] args) {
        Scontainer container=new Scontainer();
        Cook cook=new Cook(container);
        Customer customer=new Customer(container);

        cook.start();
        new Thread(customer,"小白").start();
        new Thread(customer,"小黑").start();
        new Thread(customer,"小花").start();
        new Thread(customer,"小蓝").start();
        new Thread(customer,"小绿").start();
    }
}
//生产接口
interface Producer{
    public void product();
}
//消费接口
interface Consumer{
    public void consume();

}


//生产者实现类厨师
class Cook extends Thread implements Producer{
    Scontainer container;
    public Cook(Scontainer container){
        this.container=container;
    }

    public void product(){
        for (int i = 0; i < 100; i++) {
            Chicken chicken=new Chicken(i+1);
            System.out.println("厨师生产了第"+(i+1)+"只鸡");
            container.Push(chicken);
        }
    }

    //生产鸡
    public void run(){
         product();

    }
}
//消费者实现类顾客
class Customer implements Runnable,Consumer{
    Scontainer container;
    public Customer(Scontainer container){
        this.container=container;
    }

    public void consume(){
        for (int i = 0; i < 25; i++) {
            String name=Thread.currentThread().getName();
            Chicken chicken=container.Pop();
            System.out.println(name+"购买了编号为"+chicken.id+"的鸡");
        }
    }

    //消费鸡
    public void run(){
        consume();
    }

}
//产品-->鸡
class Chicken{
    int id;
    public Chicken(int id){
        this.id=id;
    }
}
//缓冲区
class Scontainer{


    Chicken[] chickens=new Chicken[10];
    //计数器
    int count=0;


    //private final ReentrantLock lock=new ReentrantLock();
    //生产者生产鸡放入缓冲区
    public void Push(Chicken chicken){
        synchronized(this){
            while(count==chickens.length){
                //等待消费者消费
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }

            chickens[count]=chicken;
            count++;
            //通知消费者
            this.notifyAll();
        }

    }
    //消费者从缓存区拿取产品

    public synchronized Chicken Pop(){

        while (count==0){
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        count--;
        Chicken chicken=chickens[count];
        //通知生产者
        this.notifyAll();
        return chicken;

    }


}

